package com.yupi.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.yupi.project.common.BaseResponse;
import com.yupi.project.common.DeleteRequest;
import com.yupi.project.common.ErrorCode;
import com.yupi.project.common.ResultUtils;
import com.yupi.project.exception.BusinessException;
import com.yupi.project.mapper.VisitorMapper;
import com.yupi.project.model.dto.book.BookAddRequest;
import com.yupi.project.model.dto.book.BookQueryRequest;
import com.yupi.project.model.dto.book.BookUpdateRequest;
import com.yupi.project.model.dto.visitor.VisitorQueryRequest;
import com.yupi.project.model.dto.visitor.VisitorUpdateRequest;
import com.yupi.project.model.entity.Book;
import com.yupi.project.model.vo.BookVO;
import com.yupi.project.service.BookService;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 预订记录接口
 */
@RestController
@RequestMapping("/book")
public class BookController {
    @Resource
    private BookService bookService;

    @Resource
    private VisitorController visitorController;

    @Resource
    private VisitorMapper visitorMapper;

    /**
     * 创建预订记录
     *
     * @param bookAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addBook(@RequestBody BookAddRequest bookAddRequest, HttpServletRequest request) {
        if (bookAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 以下三行：计算总金额BookSum
        Long individual = bookAddRequest.getBookLevel();
        Long people = bookAddRequest.getBookPeople();
        bookAddRequest.setBookSum(individual * people);
        // 以下：通过顾客电话or第二电话，获取顾客id
        String visitorPhone = bookAddRequest.getVisitorPhone();
        Long visitorId = visitorMapper.getVisitorIdByVisitorPhone(visitorPhone);
        String visitorSecondPhone = bookAddRequest.getVisitorSecondPhone();
        Long visitorSecondId = visitorMapper.getVisitorIdByVisitorPhone(visitorSecondPhone);
        if(visitorId == null && visitorSecondId == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "该顾客尚未登记，请先在【顾客管理】模块登记该顾客！");
        }
        else if(visitorId == null && visitorSecondId != null) {
            bookAddRequest.setVisitorId(visitorSecondId);
        }
        else{
            bookAddRequest.setVisitorId(visitorId);
        }

        Book book = new Book();
        BeanUtils.copyProperties(bookAddRequest, book);
        boolean result = bookService.save(book);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }

        // 以下四行：修改顾客的活跃度
        VisitorUpdateRequest visitorUpdateRequest = new VisitorUpdateRequest();
        visitorUpdateRequest.setId(visitorId);
        visitorUpdateRequest.setVisitorActivity(bookService.getActivity(visitorId));
        visitorController.updateVisitor(visitorUpdateRequest, request);

        return ResultUtils.success(book.getId());
    }

    /**
     * 删除预订记录
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteBook(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = bookService.removeById(deleteRequest.getId());
        return ResultUtils.success(b);
    }

    /**
     * 更新预订记录
     *
     * @param bookUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateBook(@RequestBody BookUpdateRequest bookUpdateRequest, HttpServletRequest request) {
        if (bookUpdateRequest == null || bookUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long individual = bookUpdateRequest.getBookLevel();
        Long people = bookUpdateRequest.getBookPeople();
        bookUpdateRequest.setBookSum(individual * people);
        Book book = new Book();
        BeanUtils.copyProperties(bookUpdateRequest, book);
        boolean result = bookService.updateById(book);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取预订记录
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<BookVO> getBookById(int id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Book book = bookService.getById(id);
        BookVO bookVO = new BookVO();
        BeanUtils.copyProperties(book, bookVO);
        return ResultUtils.success(bookVO);
    }

    /**
     * 获取预订记录列表
     *
     * @param bookQueryRequest
     * @param request
     * @return
     */
    @GetMapping("/list")
    public BaseResponse<List<BookVO>> listBook(BookQueryRequest bookQueryRequest, HttpServletRequest request) {
        Book bookQuery = new Book();
        if (bookQueryRequest != null) {
            BeanUtils.copyProperties(bookQueryRequest, bookQuery);
        }
        QueryWrapper<Book> queryWrapper = new QueryWrapper<>(bookQuery);
        List<Book> bookList = bookService.list(queryWrapper);
        List<BookVO> bookVOList = bookList.stream().map(book -> {
            BookVO bookVO = new BookVO();
            BeanUtils.copyProperties(book, bookVO);
            return bookVO;
        }).collect(Collectors.toList());
        return ResultUtils.success(bookVOList);
    }

    /**
     * 分页获取预订记录列表
     *
     * @param bookQueryRequest
     * @param request
     * @return
     */
    @GetMapping("/list/page")
    public BaseResponse<Page<BookVO>> listBookByPage(BookQueryRequest bookQueryRequest, HttpServletRequest request) {
        long current = 1;
        long size = 10;
        Book bookQuery = new Book();
        if (bookQueryRequest != null) {
            BeanUtils.copyProperties(bookQueryRequest, bookQuery);
            current = bookQueryRequest.getCurrent();
            size = bookQueryRequest.getPageSize();
        }
        QueryWrapper<Book> queryWrapper = new QueryWrapper<>(bookQuery);
        Page<Book> bookPage = bookService.page(new Page<>(current, size), queryWrapper);
        Page<BookVO> bookVOPage = new PageDTO<>(bookPage.getCurrent(), bookPage.getSize(), bookPage.getTotal());
        List<BookVO> bookVOList = bookPage.getRecords().stream().map(book -> {
            BookVO bookVO = new BookVO();
            BeanUtils.copyProperties(book, bookVO);
            return bookVO;
        }).collect(Collectors.toList());
        bookVOPage.setRecords(bookVOList);
        return ResultUtils.success(bookVOPage);
    }
}
